package repository

import (
	"RocFamilySystem/models"
	"gorm.io/gorm"
)

type WorkTravelPayRepository struct {
	Db *gorm.DB
}

func init() {
	registerContainer["WorkTravelPayRepository"] = &WorkTravelPayRepository{}
}

func (r *WorkTravelPayRepository) SetDB(db *gorm.DB) {
	r.Db = db
}

// InsertWorkTravelPay 添加工作出差支付
func (r *WorkTravelPayRepository) InsertWorkTravelPay(workTravelPay *models.WorkTravelPay) {
	//开启事务
	db := r.Db.Begin()
	defer handleTransactional(db)
	err := db.Create(workTravelPay).Error
	handleRepositoryErr(err, "添加工作出差支付失败")
}

// DeleteWorkTravelPay 删除工作出差支付
func (r *WorkTravelPayRepository) DeleteWorkTravelPay(workTravelPayId int, loginUserId int) {
	db := r.Db.Begin()
	defer handleTransactional(db)
	err := db.Delete(&models.WorkTravelPay{Id: &workTravelPayId, CreateBy: &loginUserId}).Error
	handleRepositoryErr(err, "删除工作出差支付失败")
}

// UpdateWorkTravelPay 修改工作出差支付
func (r *WorkTravelPayRepository) UpdateWorkTravelPay(workTravelPay *models.WorkTravelPay, loginUserId int) {
	err := r.Db.Model(workTravelPay).Omit("id", "create_time").Where("create_by = ?", loginUserId).Updates(workTravelPay).Error
	handleRepositoryErr(err, "修改工作出差支付失败")
}

// SelectWorkTravelPay 查询工作出差支付
func (r *WorkTravelPayRepository) SelectWorkTravelPay(workTravelPay *models.WorkTravelPay, pageNum, pageSize int, loginUserId int) ([]models.WorkTravelPay, int) {
	var (
		list  []models.WorkTravelPay
		total int64
	)

	db := r.Db.Model(&models.WorkTravelPay{})

	db = db.Where("create_by = ?", loginUserId)

	if workTravelPay != nil {
		if workTravelPay.WorkTravelId != nil {
			db = db.Where("work_travel_id = ?", *workTravelPay.WorkTravelId)
		}
	}

	//获取总数
	db.Count(&total)

	//获取列表
	db.Offset(pageSize * pageNum).Limit(pageSize)
	db.Find(&list)

	return list, int(total)
}

// SelectWorkTravelPayById 查询工作出差支付通过ID
func (r *WorkTravelPayRepository) SelectWorkTravelPayById(id int, loginUserId int) models.WorkTravelPay {
	var workTravelPay models.WorkTravelPay
	err := r.Db.Where("create_by = ?", loginUserId).First(&workTravelPay, "id = ?", id).Error
	if err != nil {
		handleRepositoryErr(err, "查询失败")
	}
	return workTravelPay
}

// DeleteWorkTravelPayBatch 批量删除工作出差支付
func (r *WorkTravelPayRepository) DeleteWorkTravelPayBatch(ids []string, loginUserId int) {
	db := r.Db.Begin()
	defer handleTransactional(db)
	err := db.Where("id in (?)  and create_by = ? ", ids, loginUserId).Delete(models.WorkTravelPay{}).Error
	handleRepositoryErr(err, "删除工作出差支付失败！")
}
